package com.zxu.test.base;

import android.util.Log;

import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.zxu.test.network.ApiException;
import com.zxu.test.network.CustomException;
import com.zxu.test.util.Event;

public class BaseViewModel extends ViewModel {

    public static final String TAG = BaseViewModel.class.getSimpleName();

    public static final int PAGE_SIZE = 15;

    /**
     * 错误提示信息事件
     */
    public final ObservableField<Event<String>> showMessageEvent = new ObservableField<>();
    /**
     * 开始处理事件
     */
    public final ObservableField<Event<String>> startProcessEvent = new ObservableField<>();
    /**
     * 处理失败事件
     */
    public final MutableLiveData<Event<String>> failProcessEvent = new MutableLiveData<>();

    /**
     * 结束处理事件
     */
    public final ObservableField<Event<String>> successProcessEvent = new ObservableField<>();

    /**
     * 登录超时
     */
    public final ObservableField<Object> loginTimeOut = new ObservableField<>();

    public void dealThrowable(Throwable throwable) {
        String errorMessage = "请稍后再试";
        if (throwable instanceof ApiException) {
            switch (((ApiException) throwable).getCode()) {
                case CustomException.NETWORK_ERROR:
                    errorMessage = "网络异常,请检查网络";
                    break;
                case CustomException.HTTP_ERROR:
                    errorMessage = "网络异常,请检查网络";
                    break;
                case CustomException.LOGIN_OTHER_DEVICE:
                    errorMessage = "检测到您其他设备登录，请重新登录";
                    loginTimeOut.set("");
                    break;
                default:
                    errorMessage = ((ApiException) throwable).getDisplayMessage();
                    break;
            }
        }
        showMessageEvent.set(new Event<>(errorMessage));
        failProcessEvent.setValue(new Event<>(""));
        Log.e(TAG, "dealThrowable: " + errorMessage, throwable);
    }

    public void startProcess() {
        startProcessEvent.set(new Event<>(""));
    }

    public void failProcess() {
        failProcessEvent.setValue(new Event<>(""));
    }

    public void endProcess() {
        successProcessEvent.set(new Event<>(""));
    }

    public void showMessage(String message) {
        showMessageEvent.set(new Event<>(message));
    }


}

